<template>
  <el-button type="primary" v-per2="['flavor-list','post']" @click="doAdd">添加规格</el-button>
  <el-row style="margin-top:20px;">
    <el-form ref="searchFormRef" :inline="true" :model="state.searchForm">
      <el-form-item label="规格名称" prop="title">
        <el-input style="width: 200px;" v-model="state.searchForm.title" placeholder="规格名称" clearable/>
      </el-form-item>
      <el-form-item label="CPU核数" prop="vcpu">
        <el-input style="width: 100px;" v-model="state.searchForm.vcpu" placeholder="CPU核数" clearable/>
      </el-form-item>
      <el-form-item label="内存" prop="memory">
        <el-input style="width: 100px;" v-model="state.searchForm.memory" placeholder="内存" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="doSearch">搜 索</el-button>
        <el-button type="primary" @click="doResetSearchForm" plain>重 置</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="state.tableData" border style="width: 100%" v-loading="state.isLoading"
              v-per2="['flavor-list','get']">
      <el-table-column type="selection" width="55" label="选择"/>
      <el-table-column label="序号">
        <template #default="{ $index }">
          {{ $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column sortable prop="title" label="规格名称"/>
      <el-table-column sortable prop="vcpu" label="vCPU个数"/>
      <el-table-column sortable prop="memory" label="内存(GB)"/>
      <el-table-column sortable prop="desc" label="备注"/>
      <el-table-column
          v-if="hasButton([{name:'flavor-detail',method:'put'},{name:'flavor-detail',method:'delete'}])"
          label="操作">
        <template #default="scope">
          <el-popconfirm

              cancel-button-type="danger"
              confirm-button-text="确定"
              cancel-button-text="取消"
              @confirm="confirmDelete(scope.row)"
              title="确认删除吗?">
            <template #reference>
              <el-button v-per2="['flavor-detail','delete']" type="danger" size="small" icon="Delete"
                         class="card-small-btn">删 除
              </el-button>
            </template>
          </el-popconfirm>
          <el-button v-per2="['flavor-detail','put']" type="success" size="small" icon="Edit"
                     class="card-small-btn"
                     @click="doEdit(scope.row,scope.$index)">编 辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <MinePager v-per2="['flavor-list','get']" :pager="state.pager"/>
  </el-row>
  <el-dialog v-model="state.dialog.visible"
             width="50%"
             :show-close="false"
             style="padding: 0"
             draggable
             :close-on-click-modal="false"
             :close-on-press-escape="false"
  >
    <template #header="{ close, titleId, titleClass }">
      <div class="header">
        <span>{{ state.dialog.title }}</span>
        <el-link @click="close" :underline="false">
          <el-icon style="color: white">
            <Close/>
          </el-icon>
        </el-link>
      </div>
    </template>
    <div style="padding: 10px 50px">
      <el-form
          :model="state.dialog.form"
          ref="ruleForm"
          label-width="auto"
          :rules="state.dialog.rules"
      >
        <el-form-item label="规格名称" prop="title" :error="state.dialog.errors.title">
          <el-input v-model="state.dialog.form.title" placeholder="请输入规格名称"/>
        </el-form-item>
        <el-form-item label="CPU核数" prop="vcpu" :error="state.dialog.errors.vcpu">
          <el-radio-group v-model="state.dialog.form.vcpu" style="margin-right: 10px;">
            <el-radio-button v-for="item in state.dialog.options.vcpu" :label="item.label"
                             :value="item.value"/>
          </el-radio-group>
          <el-input-number
              v-model="state.dialog.form.vcpu"
              :min="1"
              :max="128"
              style="width: 80px;"
              controls-position="right"
          />
        </el-form-item>
        <el-form-item label="内存" prop="memory" :error="state.dialog.errors.memory">
          <el-radio-group v-model="state.dialog.form.memory" style="margin-right: 10px;" @click="doClickUnit">
            <el-radio-button v-for="item in state.dialog.options.memory" :label="item.label"
                             :value="item.value"/>
          </el-radio-group>
          <el-input-number
              v-model="state.dialog.form.memory"
              :min="1"
              style="width: 120px;margin-right: 10px;"
              controls-position="right"
          />
          <el-select v-model="state.dialog.unit" style="width: 80px;" @change="doChangeUnit">
            <el-option
                v-for="item in state.dialog.options.unit"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="desc" :error="state.dialog.errors.desc">
          <el-input v-model="state.dialog.form.desc" type="textarea" maxlength="200" show-word-limit :rows="4"/>
        </el-form-item>
        <el-row :gutter="50" justify="center" align="middle" style="height: 80px">
          <el-form-item>
            <el-button @click="state.dialog.doSubmit" type="primary" style="width: 150px;height: 40px">提 交</el-button>
            <el-button @click="state.dialog.visible = false" type="primary" style="width: 150px;height: 40px">取 消
            </el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
  </el-dialog>

</template>

<script setup>
import {onMounted, reactive, ref} from "vue";
import _axios from "@/plugin/axios.js";
import {ElMessage} from "element-plus";
import MinePager from "@/components/MinePager.vue";
import {hasPermission2, hasButton} from "@/stores/permission.js";
import {clearFormError} from "@/plugin/form.js";


const searchFormRef = ref(null)
const ruleForm = ref(null)
const state = reactive({
  isLoading: false,
  tableData: [],
  pager: {
    currentPage: 1,
    totalCount: 0,
    perPageSize: Number(localStorage.getItem("pageSize")) || 10,
    handleSizeChange: handleSizeChange,
    handleChangePage: handleChangePage
  },
  editId: -1,
  editIndex: -1,
  dialog: {
    visible: false,
    title: "",
    unit: "GiB",
    form: {
      title: "",
      vcpu: "",
      memory: "",
      desc: ""
    },
    options: {
      vcpu: [
        {value: 2, label: "2核"},
        {value: 4, label: "4核"},
        {value: 8, label: "8核"},
        {value: 16, label: "16核"},
        {value: 32, label: "32核"},
        {value: 64, label: "64核"},
        {value: 128, label: "128核"},
      ],
      memory: [
        {value: 4, label: "4GiB"},
        {value: 8, label: "8GiB"},
        {value: 16, label: "16GiB"},
        {value: 32, label: "32GiB"},
        {value: 64, label: "64GiB"},
        {value: 128, label: "128GiB"}
      ],
      unit: [
        {value: "GiB", label: "GiB"},
        {value: "MiB", label: "MiB"}
      ]
    },
    errors: {
      title: "",
      vcpu: "",
      memory: "",
      desc: ""
    },
    rules: {
      title: [
        {required: true, message: '请输规格名称', trigger: 'blur'},
      ],
      vcpu: [
        {required: true, message: '请输入CPU核数', trigger: 'blur'},
      ],
      memory: [
        {required: true, message: '请输入内存大小', trigger: 'blur'},
      ],
      desc: [
        {required: true, message: '请输规格名称', trigger: 'blur'},
      ]
    },
    doSubmit: doSubmit
  },
  searchForm: {
    title: "",
    vcpu: "",
    memory: ""
  }
})


onMounted(() => {
  initTableData()
})

function doResetSearchForm() {
  searchFormRef.value.resetFields()
}

function doSearch() {
  state.pager.currentPage = 1
  initTableData()
}

function doChangeUnit(value) {
  if (value === "MiB") {
    state.dialog.form.memory = state.dialog.form.memory * 1024
  } else {
    state.dialog.form.memory = state.dialog.form.memory / 1024
  }
}

function doClickUnit() {
  if (state.dialog.unit !== "GiB") {
    state.dialog.unit = "GiB"
  }
}

function initTableData() {
  if (hasPermission2("flavor-list", "get")) {
    let search_params = {page: state.pager.currentPage, page_size: state.pager.perPageSize}
    for (let key in state.searchForm) {
      let value = state.searchForm[key]
      search_params[key] = value
    }
    _axios.get("/api/web/flavor/", {params: search_params}).then((res) => {
      if (res.data.code === 0) {
        state.tableData = res.data.data.data;
        state.pager.totalCount = res.data.data.totalCount;
        state.pager.perPageSize = res.data.data.perPageSize
      }
    })
  }
}


function handleChangePage(page) {
  state.pager.currentPage = page
  initTableData()
}

function handleSizeChange(page_size) {
  localStorage.setItem("pageSize", page_size)
  state.pager.perPageSize = page_size
  state.pager.currentPage = 1
  initTableData()
}

function doAdd() {
  state.dialog.visible = true
  state.dialog.title = "添加规格"
  state.editId = -1
  state.editIndex = -1
  clearFormError(state.dialog.errors)
  state.dialog.form = {
    title: "",
    vcpu: 2,
    memory: 4,
    desc: ""
  }
}

function doEdit(row, index) {
  clearFormError(state.dialog.errors)
  state.dialog.visible = true
  state.dialog.title = '编辑规格'
  state.editId = row.id
  state.editIndex = index
  let dict = state.tableData[index]
  state.dialog.form = {
    title: dict.title,
    vcpu: dict.vcpu,
    memory: dict.memory,
    desc: dict.desc
  }
}

function confirmDelete(row) {
  _axios.delete(`/api/web/flavor/${row.id}/`).then((res) => {
    if (res.data.code === 0) {
      state.tableData = state.tableData.filter((item) => {
        return row.id !== item.id
      })
      ElMessage.success("删除成功")
    } else {
      ElMessage.error("删除失败")
    }
  })
}

function doSubmit() {
  ruleForm.value.validate((valid, fields) => {
    if (valid) {
      if (state.dialog.unit!=="GiB"){
        state.dialog.form.memory =  state.dialog.form.memory / 1024
      }
      if (state.editId > 0) {
        _axios.patch(`/api/web/flavor/${state.editId}/`, state.dialog.form).then((res) => {
          if (res.data.code === 0) {
            state.tableData[state.editIndex] = res.data.data
            state.editId = -1
            state.editIndex = -1
            state.dialog.visible = false
          } else if (res.data.code === 2001) {
            for (let key in res.data.detail) {
              state.dialog.errors[key] = res.data.detail[key][0]
            }
          } else {
            ElMessage.error("编辑失败")
          }
        })
      } else {
        state.dialog.errors = {}
        _axios.post('/api/web/flavor/', state.dialog.form).then((res) => {
          if (res.data.code === 0) {
            //state.tableData.unshift(res.data.data)
            state.dialog.visible = false
            initTableData()
          } else if (res.data.code === 2001) {
            for (let key in res.data.detail) {
              state.dialog.errors[key] = res.data.detail[key][0]
            }
          } else {
            ElMessage.error("添加失败")
          }
        })
      }
    }
  })
}


</script>

<style scoped>
.header {
  color: #FFFFFF;
  height: 48px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  background-color: rgb(51.2, 126.4, 204);

}
</style>